package com.tom.rpc.v2;

import com.tom.rpc.v2.common.RpcRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * rpc客户端代理
 *
 * @author yanghongjun19
 * @date 2021/01/06
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RpcProxy {

    private RpcClient rpcClient;

    public <T> T getProxy(Class<T> interfaceClass) {
        T proxyInstance = (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                RpcRequest request = new RpcRequest();
                request.setClassName(interfaceClass.getSimpleName());
                request.setMethodName(method.getName());
                request.setParameters(args);
                request.setParameterTypes(method.getParameterTypes());
                Object result = rpcClient.send(request);
                return result;
            }
        });

        return proxyInstance;
    }
}
